package com.jh.jingfei.main;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.jh.jingfei.MyApplication;
import com.jh.jingfei.R;
import com.jh.jingfei.login.ui.LoginFragment;
import com.jh.jingfei.models.Account;
import com.jh.jingfei.repositories.AccountRepository;
import com.strongloop.android.loopback.AccessToken;
import com.strongloop.android.loopback.RestAdapter;
import com.strongloop.android.loopback.callbacks.ObjectCallback;

import me.yokeyword.fragmentation_swipeback.SwipeBackActivity;

public class MainActivity extends SwipeBackActivity {

    /**
     * 如果是从welcomeActivity中进入该页面，说明用户的id和token获取到，
     * 那么直接加载用户数据
     */
    public static final String LOAD_USER_INFO = "LOAD_USER_INFO";

    private MyApplication application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        application = (MyApplication) getApplication();

        Intent intent = getIntent();

        Bundle bundle = intent.getExtras();

        if (bundle != null) {

            boolean fa = bundle.getBoolean(LOAD_USER_INFO);

            if (fa) {
                loadUserInfo();
            }
        }


        if (findFragment(MainFragment.class) == null) {
            loadRootFragment(R.id.main_content, MainFragment.newInstance("", ""));  //load root Fragment
        }
    }

    /**
     * 根据用户的userId 和token 加载用户信息
     */
    private void loadUserInfo() {
        Log.i("load user info", "=====");
        RestAdapter restAdapter = new RestAdapter(this, getString(R.string.base_url));
        AccountRepository up = restAdapter.createRepository(AccountRepository.class);

        up.findById(application.getUserId(), new ObjectCallback<Account>() {
            @Override
            public void onSuccess(Account object) {
                application.setAccount(object);
            }

            @Override
            public void onError(Throwable t) {

            }
        });
    }
}
